package com.asimplefox.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.asimplefox.configs.FileConfig;
import com.asimplefox.entity.Role;
import com.asimplefox.entity.User;
import com.asimplefox.entity.vo.UserReVo;
import com.asimplefox.mapper.UserMapper;
import com.asimplefox.serurity.TokenManager;
import com.asimplefox.serurity.UserRoleDetails;
import com.asimplefox.service.IRoleService;
import com.asimplefox.service.IUserService;
import com.asimplefox.service.abst.ServiceImplAll;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author kloping
 * @since 2024-10-14
 */
@Service
public class UserServiceImpl extends ServiceImplAll<UserMapper, User> implements IUserService {
    @Override
    public Object list(Integer pageSize, Integer pageNum) {
        Page<User> page = new Page<>(pageNum, pageSize);
        page.addOrder(OrderItem.desc("id"));
        IPage<User> ipage = this.page(page);
        ipage = this.page(ipage);
        ipage.getRecords().forEach(e -> e.setPwd(""));
        return ipage;
    }

    @Override
    public Object addUser(UserReVo userVo, HttpServletResponse rsp) {
        User user = new User();
        user.setUsername(userVo.getUsername());
        user.setPwd(userVo.getPassword());
        user.setNickname(userVo.getNickname());
        user.setTelephone(userVo.getTelephone());
        user.setEmail(userVo.getEmail());
        User dup = this.lambdaQuery().eq(User::getUsername, user.getUsername()).one();
        if (dup != null) {
            rsp.setStatus(400);
            return fail("username唯一字段不可重复");
        }
        if (this.save(user)) {
            return result(200, "ok", "id", user.getId());
        } else {
            rsp.setStatus(500);
            return error("error");
        }
    }

    @Autowired
    FileConfig fileConfig;

    @Override
    public Object modify(Integer id, MultipartFile avatar, String nickname, HttpServletResponse rsp, UserRoleDetails userDetails) {
        User user;
        if (id != null) {
            if (userDetails.getUser().getId() != id) {
                boolean has = false;
                for (GrantedAuthority authority : userDetails.getAuthorities()) {
                    if (authority.getAuthority().equalsIgnoreCase(TokenManager.ADMIN)) {
                        has = true;
                    }
                }
                if (!has) {
                    rsp.setStatus(403);
                    return define("权限不足");
                }
            }
            user = this.getById(id);
        } else {
            user = this.lambdaQuery().eq(User::getUsername, userDetails.getUsername()).one();
            id = user.getId();
        }
        int s = 0;
        if (avatar != null) {
            FileConfig.FileWithPath fileWithPath = fileConfig.getFileWithPath("avatar/", id + ".jpg");
            try {
                fileWithPath.write(avatar.getBytes());
            } catch (IOException e) {
                System.err.println(e.getMessage());
                rsp.setStatus(500);
                return error("头像上传失败");
            }
            user.setAvatar(fileWithPath.getUrl());
            s++;
        }
        if (nickname != null) {
            user.setNickname(nickname);
            s++;
        }
        if (s > 0) {
            if (this.updateById(user)) {
                return result(200, "ok", "count", s);
            } else return result(500, "error", "msg", "服务异常");
        } else {
            rsp.setStatus(400);
            return fail("未上传任何需修改信息");
        }
    }

    @Autowired
    IRoleService roleService;

    @Override
    public Object listAdmins() {
        List<Role> roles = roleService.lambdaQuery().eq(Role::getUserRole, "admin")
                .or().eq(Role::getUserRole, "system").list();
        Set<Integer> userIds = roles.stream().map(Role::getUserId).collect(Collectors.toSet());
        JSONArray results = new JSONArray();
        for (Integer userId : userIds) {
            User user = this.getById(userId);
            JSONObject jo = (JSONObject) JSON.toJSON(user);
            JSONArray rs = new JSONArray();
            for (Role role : roles) {
                if (role.getUserId().equals(userId)) {
                    rs.add(role.getUserRole());
                }
            }
            jo.put("roles", rs);
            results.add(jo);
        }
        return results;
    }
}
